<?php

/**
 * tournament actions.
 *
 * @package    bolao-aabb
 * @subpackage tournament
 * @author     Your name here
 */
class tournamentActions extends sfActions
{
  public function executeIndex(sfWebRequest $request)
  {
    // Get tournaments order by date
    $criteria = new Criteria();
    $criteria->addAscendingOrderByColumn(BolaoTournamentPeer::START_DATE);
    $this->tournaments = BolaoTournamentPeer::doSelect($criteria);
  }

  public function executeShow(sfWebRequest $request)
  {
    if ($request->hasParameter('id'))
    {
      $this->BolaoTournament = BolaoTournamentPeer::retrieveByPk($request->getParameter('id'));
    }
    else
    {
      $this->BolaoTournament = BolaoTournamentPeer::retrieveByNameAndYear($request->getParameter('name_slug'), $request->getParameter('year'), $request->getParameter('category_slug'), $request->getParameter('subcategory_slug'));
    }

    $this->forward404Unless($this->BolaoTournament);

    // Parse XML file
    $xml = simplexml_load_file('uploads/tournaments/'.$this->BolaoTournament->getScoresheet());

    // Map championship data to array
    $championship = array();
    $championship['name'] = (string) $xml->name;
    $championship['type'] = (string) $xml->type;
    $championship['team'] = array();
    $championship['team']['type']     = (string) $xml->teamType;
    $championship['team']['modality'] = (string) $xml->teamModality;

    // Map teams to array indexed by ID
    $teams = array();
    foreach($xml->teams->team as $team)
    {
      $team_id = (integer) $team['id'];
      $teams[$team_id] = array();
      $teams[$team_id]['name'] = (string) $team->name;
    }

    // Map players to array by ID
    $players = array();
    foreach ($xml->teams->team as $team)
    {
        $team_id = (integer) $team['id'];

        // Read team playes indexed by ID
        foreach ($team->players->player as $player)
        {
          $player_id = (integer) $player['id'];
          $players[$player_id] = array();
          $players[$player_id]['name'] = (string) $player->name;
          $players[$player_id]['team_id'] = $team_id;
          $players[$player_id]['modality'] = (string) $player->modality;
        }
    }

    // Map games to array indexed by ID
    $games = array();
    foreach ($xml->games->game as $game)
    {
      $game_id = (integer) $game['id'];
      $game_data = array();

      // Read game data
      $game_data['place'] = (string) $game->place;
      $game_data['date']  = strtotime($game->date);
      if (count($game->teams) > 0)
      {
        $game_data['teams'] = array();
        foreach ($game->teams->team as $team)
        {
          $game_data['teams'][] = (integer) $team['reference'];
        }
        $game_data['points'] = array();
      }
      foreach ($game->players->gameplayer as $gameplayer)
      {
        $player_id = (integer) $gameplayer->player['reference'];
        $point = array();
        $point['sum']       = (integer) $gameplayer->sum;
        $point['summed']    = (string) $gameplayer->summed;
        $game_data['points'][$player_id] = $point;
      }

      $games[$game_id] = $game_data;
    }

    // Map phases to array indexed by ID
    $phases = array();
    foreach ($xml->phases->phase as $phase)
    {
      $phase_id = (integer) $phase['id'];
      $phase_data = array();

      // Get phase data
      $phase_data['groups'] = array();
      foreach ($phase->groups->group as $group)
      {
        $group_id = (integer) $group['id'];
        $group_data = array();

        // Get group data
        $group_data['name']  = (string) $group->name;
        $group_data['games'] = array();
        foreach ($group->games->game as $game_ref)
        {
          $group_data['games'][] = (integer) $game_ref['reference'];
        }
        $group_data['teams'] = array();
        foreach ($group->teams->teampointer as $team)
        {
          $group_data['teams'][] = (integer) $team->fixedTeam['reference'];
        }
        $group_data['finished'] = (boolean) $group->finished;

        // Save group data to array
        $phase_data['groups'][$group_id] = $group_data;
      }
      switch($phase->classificationAlgorithm['class'])
      {
        case "org.jader.bolao.classificationalgorithm.ClassifyByPoints":
          $phase_data['ca'] = array();
          $phase_data['ca']['type'] = "ClassifyByPoints";
          $points = array();
          for($i=1; $i<21; $i++)
            $points[$i] = (integer) $phase->classificationAlgorithm->points->int[$i];
          $phase_data['ca']['points'] = $points;
          break;

        default:
          $phase_data['ca']['type'] = "Unknown";
      }
      $phase_data['game_type'] = (string) $phase->gameType;
      
      // Save phase data to array
      $phases[$phase_id] = $phase_data;
    }

    // Map custom modality to array indexed by ID
    $modalities = array();
    if (count($xml->customModalities) > 0)
    {
      foreach ($xml->customModalities->modality as $modality)
      {
        $modality_id = (integer) $modality['id'];
        $modality_data = array();
        
        // Read modality data
        $modality_data['name'] = (string) $modality->name;
        if (count($modality->teams) > 0)
        {
          $modality_data['teams'] = array();
          foreach ($modality->teams->modalityTeam as $team)
          {
            $team_id = (integer) $team['id'];
            $modality_data['teams'][$team_id] = array();
            $modality_data['teams'][$team_id]['name'] = (string) $team->name;
            $modality_players = array();
            foreach($team->players->player as $player)
            {
              $modality_players[] = (integer) $player['reference'];
            }
            $modality_data['teams'][$team_id]['players'] = $modality_players;
          }
        }
        
        $modalities[$modality_id] = $modality_data;
      }
    }

    // Assign template variables
    $this->championship = $championship;
    $this->teams        = $teams;
    $this->players      = $players;
    $this->games        = $games;
    $this->phases       = $phases;
    $this->modalities   = $modalities;
  }

  public function executeNew(sfWebRequest $request)
  {
    $tournament = new BolaoTournament();
    $tournament->setCreatorId($this->getUser()->getProfile()->getUserId());
    $this->form = new BolaoTournamentForm($tournament);
  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));

    $this->form = new BolaoTournamentForm();

    $this->processForm($request, $this->form);

    $this->setTemplate('new');
  }

  public function executeEdit(sfWebRequest $request)
  {
    $this->forward404Unless($BolaoTournament = BolaoTournamentPeer::retrieveByPk($request->getParameter('id')), sprintf('Object BolaoTournament does not exist (%s).', $request->getParameter('id')));
    $this->form = new BolaoTournamentForm($BolaoTournament);
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($BolaoTournament = BolaoTournamentPeer::retrieveByPk($request->getParameter('id')), sprintf('Object BolaoTournament does not exist (%s).', $request->getParameter('id')));
    $this->form = new BolaoTournamentForm($BolaoTournament);

    $this->processForm($request, $this->form);

    $this->setTemplate('edit');
  }

  public function executeDelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();

    $this->forward404Unless($BolaoTournament = BolaoTournamentPeer::retrieveByPk($request->getParameter('id')), sprintf('Object BolaoTournament does not exist (%s).', $request->getParameter('id')));
    $BolaoTournament->delete();

    $this->redirect('tournament/index');
  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $tournament = $form->save();

      if ($form['send_email']->getValue())
        $this->redirect('@send_email?type=tournament&id='.$tournament->getId());
      else
      {
        if ($tournament->getBolaoSubcategory() != null)
        {
          $category_slug    = $tournament->getBolaoSubcategory()->getCategory()->getNameSlug();
          $subcategory_slug = $tournament->getBolaoSubcategory()->getNameSlug();
        }
        else
          $category_slug = $subcategory_slug = "";
        
        $this->redirect('@show_tournament_by_name?year='.$tournament->getYear().'&name_slug='.$tournament->getNameSlug().'&category_slug='.$category_slug.'&subcategory_slug='.$subcategory_slug);
      }
    }
  }
}
